package com.jyniubi.gmail.wms.listener;

import com.alibaba.fastjson.JSON;
import com.jyniubi.gmail.wms.entity.WareSkuEntity;
import com.jyniubi.gmail.wms.mapper.WareSkuMapper;
import com.jyniubi.gmail.wms.vo.SkuLockVo;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;


@Component
public class StockListener {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private WareSkuMapper wareSkuMapper;

    private static final String KEY_PREFIX = "stock:info:";

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("STOCK.MINUS.QUEUE"),
            exchange = @Exchange(value = "ORDER.EXCHANGE",type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = {"order.minus"}
    ))
    public void minus(String orderToken, Channel channel, Message message) throws IOException {
        // orderToken判空
        if (StringUtils.isBlank(orderToken)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        // 从redis中取出锁定的商品信息
        String json = this.redisTemplate.opsForValue().get(KEY_PREFIX + orderToken);
        // 如果为空则确认结束
        if (StringUtils.isBlank(json)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        // 如果不为空序列化为锁定信息集合，遍历解锁库存
        List<SkuLockVo> skuLockVos = JSON.parseArray(json, SkuLockVo.class);
        if (CollectionUtils.isEmpty(skuLockVos)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        // 更新数据库订单表中的数量
        skuLockVos.forEach(skuLockVo -> {
            this.wareSkuMapper.minus(skuLockVo.getWareSkuId(),skuLockVo.getCount());
        });
        // 删除redis中缓存的数据
        this.redisTemplate.delete(KEY_PREFIX + orderToken);

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("STOCK.UNLOCK.QUEUE"),
            exchange = @Exchange(value = "ORDER.EXCHANGE",type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = {"order.fail","stock.unlock"}
    ))
    public void unlock(String orderToken, Channel channel, Message message) throws IOException {
        // orderToken判空
        if (StringUtils.isBlank(orderToken)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        // 从redis中取出锁定的商品信息
        String json = this.redisTemplate.opsForValue().get(KEY_PREFIX + orderToken);
        // 如果为空则确认结束
        if (StringUtils.isBlank(json)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        // 如果不为空序列化为锁定信息集合，遍历解锁库存
        List<SkuLockVo> skuLockVos = JSON.parseArray(json, SkuLockVo.class);
        if (CollectionUtils.isEmpty(skuLockVos)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        skuLockVos.forEach(skuLockVo -> {
            this.wareSkuMapper.unlock(skuLockVo.getWareSkuId(),skuLockVo.getCount());
        });
        // 删除redis中缓存的数据
        this.redisTemplate.delete(KEY_PREFIX + orderToken);

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
